package com.boarsoft.rpc.adapter;

import java.util.Date;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.common.util.InetUtil;
import com.boarsoft.rpc.bean.RpcRegistry;
import com.boarsoft.rpc.core.RpcContext;
import com.boarsoft.rpc.listener.RpcListener;

/**
 * 从mac-rpc获取所有节点的注册信息，以获取HTTP请求应转发的目标地址
 * 
 * @author Mac_J
 *
 */
public class ZoneInfoRpcListenerImpl implements RpcListener {
	private static final Logger log = LoggerFactory.getLogger(ZoneInfoRpcListenerImpl.class);

	@Autowired
	protected RpcContext rpcContext;

	@Override
	public void onRemoveLink(String addr, String reason) {
		// Nothing to do
	}

	@Override
	public void onRegister(RpcRegistry reg) {
		// Nothing to do
	}

	@Override
	public void onDeregister(RpcRegistry reg) {
		// Nothing to do
	}

	@Override
	public void onUpdateRegistry(RpcRegistry rr) {
		String addr = rr.getKey();
		// 不检查自己的注册表
		if (InetUtil.getAddr().equals(addr)) {
			return;
		}
		Properties rm = rr.getMeta();
		Date rv = (Date) rm.get("zone.version");
		if (rv == null) {
			return;
		}
		RpcRegistry mr = rpcContext.getMyRegistry();
		Properties mm = mr.getMeta();
		Date mv = (Date) mm.get("zone.version");
		if (mv == null || mv.before(rv)) {
			log.warn("Update zone info from {}", rr.getKey());
			Properties p = rr.getMeta();
			for (Object k: p.keySet()) {
				String s = String.valueOf(k);
				Object v = p.get(k);
				if (s.startsWith("zone.")) {
					log.debug("Update zone info {}={}", s, v);
					mm.put(k, v);
				}
			}
		}
	}

	public RpcContext getRpcContext() {
		return rpcContext;
	}

	public void setRpcContext(RpcContext rpcContext) {
		this.rpcContext = rpcContext;
	}

}
